local HttpClient = require "http.httpc"
local Json = require "lualib.Json"
local HttpUrl = require "http.url"
local table = table
local type = type

local M = {}

local function params2content(params)
    if not params then
        return
    end

    if type(params) == "string" then
        return params
    end

    -- params is a table
    local query = {}
    for k, v in pairs(params) do
        table.insert(query, string.format("%s=%s", k, v))
    end

    return table.concat(query, "&")
end

function M.request(method, domain, uri, params, recvheader, header)
    local content = params2content(params)
    return HttpClient[method:lower()](domain, uri, recvheader, header, params, content)
end

function M.get(domain, uri, params, recvheader, header)
    return M.request('GET', domain, uri, params, recvheader, header)
end

function M.post(domain, uri, params, recvheader, header)
    return M.request('POST', domain, uri, params, recvheader, header)
end

function M.json(domain, uri, params, recvheader, header)
    header["content-type"] = "application/json"
    if params then
        params = Json.encode(params)
    end

    return M.request("POST", domain, uri, params, recvheader, header)
end

return M
